//
//  NSString+Emoticon.swift
//  微博内容转表情
//
//  Created by 柴瑞军 on 16/4/26.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit

extension String{

    //将微博中的表情字符串替换成表情图片
    func emoticonNameTextToPicAttText() -> NSAttributedString {
        let attrText = NSMutableAttributedString(string: self)
        
        //正则表达式
        let pattern = "\\[.*?\\]"
        
        let regular  = try! NSRegularExpression(pattern: pattern, options: [])
        
        //匹配
        let results  = regular.matchesInString(self, options: [], range: NSRange(location: 0, length: characters.count))
        //遍历匹配以后的结果
        for result in results.reverse()  {
            //一个结果有一个范围
            let num = result.numberOfRanges
            print("num: \(num)")
            //取出每个结果的范围
            let range = result.rangeAtIndex(0)
            print("\(range)")
            
            //截取匹配的名称
            let emoticonName = (self as NSString).substringWithRange(range)
            print("匹配的结果:\(emoticonName)")
            
            //用表情名称去找模型
            if let emoticonModel = ALEmoticonModel.emoticonNameToEmoticonModel(emoticonName) {
                //将图片转换成带属性的属性文本
                let attrStr = emoticonModel.emoticonModelToAttrText(UIFont.systemFontOfSize(15))
                //将表情名称转换为属性文本
                
                attrText.replaceCharactersInRange(range, withAttributedString: attrStr)
            }
        }
        return attrText
    }
}